package com.example.shardingjdbc.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.example.shardingjdbc.model.DictTable;
import com.example.shardingjdbc.model.Member;
import com.example.shardingjdbc.model.Order;
import com.example.shardingjdbc.model.OrderItem;
import com.example.shardingjdbc.service.MemberSevice;
import com.example.shardingjdbc.service.OrderService;
import com.example.shardingjdbc.shardingMapper.DictTableMapper;
import com.example.shardingjdbc.shardingMapper.OrderItemMapper;
import com.example.shardingjdbc.shardingMapper.OrderMapper;
import com.example.shardingjdbc.utils.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.transaction.annotation.ShardingTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Random;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private OrderItemMapper orderItemMapper;
	@Autowired
	private MemberSevice memberService;
	@Autowired
	private DictTableMapper dictTableMapper;


	@Transactional
	@ShardingTransactionType(TransactionType.XA)
	public String insertOrder() {
		Member member = memberService.insertMember();
		log.info("insert member success:{}", JSON.toJSONString(member));
		//Member member = new Member();
		//member.setMemberId(123232l);
		DictTable dictTable = dictTableMapper.selectByPrimaryKey(1);
		log.info("dictTable:{}",JSON.toJSONString(dictTable));
		for(int i = 1; i <= 10; i++){
			Order record = new Order();
			long orderId = IdWorker.getLongId();
			record.setOrderId(orderId);
			record.setCreatedDate(new Date());
			record.setDeleteFlag("0");
			record.setMemberId(0l + i);
			record.setStatus("gc101");
			record.setTotalAccount(new BigDecimal("125.00"));
			orderMapper.insertSelective(record);

			OrderItem item1 = new OrderItem();
			long itemId = IdWorker.getLongId();
			item1.setItemId(itemId);
			item1.setCreatedDate(new Date());
			item1.setItemAccount(110l);
			item1.setMemberId(record.getMemberId());
			item1.setProductName("狗皮膏药"+i);
			item1.setOrderId(record.getOrderId());
			orderItemMapper.insertSelective(item1);
		}

/*		int randomException = new Random().nextInt(2);
		log.info("randomException:{}", randomException);
		if(randomException % 2 == 0){
			throw new RuntimeException("运行时异常了");
		}*/
		
		JSONObject result = new JSONObject();
		JSONArray arr = new JSONArray();
		//arr.add(item1);
		//result.put("dictTable", dictTable);
		result.put("member", member);
		//result.put("order", record);
		result.put("items", arr);
		return result.toJSONString();
	}

}
